package com.xjcs.saplingplan.ui.callback

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.xjcs.saplingplan.adapter.CountdownCateAdapter
import com.xjcs.saplingplan.const.dpToPx

class ItemTouchHelperCallback(private val context: Context, private val adapter: CountdownCateAdapter)
    : ItemTouchHelper.Callback() {

    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        return makeMovementFlags(
            ItemTouchHelper.UP or ItemTouchHelper.DOWN,
            ItemTouchHelper.RIGHT
        )
    }

    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        // 获取被拖动 item 的位置 和 目标位置
        val fromPosition = viewHolder.adapterPosition
        val toPosition = target.adapterPosition
        // 通知 Adapter 数据顺序发生变化（你需要实现这个方法）
        adapter.onItemMove(fromPosition, toPosition)
        return true
    }

    // 可选：当拖动状态改变时的回调，比如开始拖动、松开等
    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            // 拖动开始，可以加个背景色或者动画提示
            viewHolder?.itemView?.alpha = 0.5f
        } else if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            //侧滑时的效果
            viewHolder?.itemView?.alpha = 0.8f
        }
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        super.clearView(recyclerView, viewHolder)
        //恢复拖动item的背景透明度
        viewHolder.itemView.alpha = 1f
        // 获取拖动完成后最新的数据顺序
        val latestOrder = adapter.getData()
        // 通知外部监听器：拖动完成，可以保存了
        adapter.dragFinishCallback.invoke(latestOrder)
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        // 获取被侧滑的item的位置
        val position = viewHolder.adapterPosition
        if (position in 0 until adapter.itemCount) {
            val deletedItem = adapter.getData()[position]
            // 回调删除事件
            adapter.onItemDelete.invoke(position, deletedItem)
        }
    }

    override fun onChildDraw(
        canvas: Canvas,
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        dX: Float,
        dY: Float,
        actionState: Int,
        isCurrentlyActive: Boolean
    ) {
        //在这里自定义侧滑时的UI效果
        val itemView = viewHolder.itemView
        val isCanceled = dX == 0f && !isCurrentlyActive

        if(isCanceled){
            clearCanvas(canvas, itemView.right + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat())
            super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
            return
        }

        if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
            // 只在滑动时绘制删除背景和文字，不要和拖动混淆
            val backgroundColor = android.graphics.Color.parseColor("#f44336")
            val paint = Paint()
            paint.color = backgroundColor
            val right = itemView.right.toFloat()         // item 最右边
            val left = right - dX                         // 背景从 item.right 往左延伸 dX 的宽度
            val top = itemView.top.toFloat()
            val bottom = itemView.bottom.toFloat()

            // 只有当 dX > 0 （向右滑动）时才绘制
            if (dX > 0) {
                canvas.drawRect(left, top, right, bottom, paint)

                // 绘制“删除”文字，居中显示在删除背景上
                val deleteText = "删除"
                val textPaint = Paint()
                textPaint.color = android.graphics.Color.WHITE
                textPaint.textSize = 16.dpToPx(context).toFloat()
                textPaint.textAlign = Paint.Align.CENTER

                val textWidth = textPaint.measureText(deleteText)
                // 背景区域：left ~ right
                val textX = left + (right - left) / 2  // 背景区域中心
                val textY = top + (bottom - top) / 2 + (textPaint.descent() - textPaint.ascent()) / 2 - textPaint.descent()

                canvas.drawText(deleteText, textX, textY, textPaint)
            }
        }

//        //设置侧滑背景色
//        val backgroundColor = android.graphics.Color.parseColor("#f44336")
//        val paint = Paint()
//        paint.color = backgroundColor
//        val left = itemView.left.toFloat()
//        val right = itemView.left + dX
//        val top = itemView.top.toFloat()
//        val bottom = itemView.bottom.toFloat()
//
//        canvas.drawRect(left, top, right, bottom, paint)
//
//        // 可选：在侧滑背景上绘制删除图标或文字
//        val deleteText = "删除"
//        val textPaint = Paint()
//        textPaint.color = android.graphics.Color.WHITE
//        textPaint.textSize = SizeUtils.dp2px(24f).toFloat() // sp转px需要处理，这里简化处理
//        textPaint.textAlign = Paint.Align.CENTER
//
//        val textWidth = textPaint.measureText(deleteText)
//        val textX = itemView.left + dX / 2 - textWidth / 2
//        val textY = itemView.top + (itemView.bottom - itemView.top) / 2 + (textPaint.descent() - textPaint.ascent()) / 2 - textPaint.descent()
//
//        canvas.drawText(deleteText, textX, textY, textPaint)
//
//        super.onChildDraw(canvas, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
    }

    private fun clearCanvas(c: Canvas?, left: Float, top: Float, right: Float, bottom: Float) {
        c?.drawRect(left, top, right, bottom, Paint())
    }
}